/**
 * FileName: CarouselServiceImpl
 * Author:   sky
 * Date:     2019/12/27 09:22
 * Description:
 */
package com.run.guifeng.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.run.guifeng.dao.CarouselMapper;
import com.run.guifeng.model.entity.Carousel;
import com.run.guifeng.model.enums.ServiceResultEnum;
import com.run.guifeng.model.vo.IndexCarouselVO;
import com.run.guifeng.service.CarouselService;
import com.run.guifeng.util.BeanUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 *
 *
 * @author sky
 * @create 2019/12/27
 * @since 1.0.0
 */
@Service
public class CarouselServiceImpl implements CarouselService {

    @Resource
    private CarouselMapper carouselMapper;

    @Override
    public List<Carousel> getCarouselPage() {
        return carouselMapper.selectList(Wrappers.<Carousel>lambdaQuery().eq(Carousel::getDeleted, false));
    }

    @Override
    public String saveCarousel(Carousel carousel) {
        if (carouselMapper.insert(carousel) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String updateCarousel(Carousel carousel) {
        Carousel temp = carouselMapper.selectById(carousel.getId());
        if (temp == null) {
            return ServiceResultEnum.DATA_NOT_EXIST.getResult();
        }
        temp.setCarouselRank(carousel.getCarouselRank());
        temp.setRedirectUrl(carousel.getRedirectUrl());
        temp.setCarouselUrl(carousel.getCarouselUrl());
        temp.setUpdateTime(new Date());
        if (carouselMapper.updateById(temp) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public Carousel getCarouselById(Integer id) {
        return carouselMapper.selectById(id);
    }

    @Override
    public String deleteBatch(Integer[] ids) {
        if (ids.length < 1) {
            return ServiceResultEnum.ERROR.getResult();
        }
        //删除数据
        if (carouselMapper.deleteBatchIds(Arrays.asList(ids)) == ids.length) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.OPERATE_ERROR.getResult();
    }


    @Override
    public List<IndexCarouselVO> getCarouselsForIndex(int number) {
        List<IndexCarouselVO> indexCarouselVOS = new ArrayList<>(number);
        List<Carousel> carousels = carouselMapper.selectList(Wrappers
                .<Carousel>lambdaQuery().eq(Carousel::getDeleted, false).orderByDesc(Carousel::getCarouselRank));
        if (!CollectionUtils.isEmpty(carousels)) {
            indexCarouselVOS = BeanUtil.copyList(carousels, IndexCarouselVO.class);
        }
        return indexCarouselVOS;
    }
}